package com.example.android.BluetoothChat;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;

public class AudioPlayer implements OnCompletionListener, OnErrorListener,
		OnPreparedListener {
	private MediaPlayer mediaPlayer;

	public AudioPlayer(Context context, File file) {
		if (mediaPlayer == null) {
			// 创建播放实例
			mediaPlayer = new MediaPlayer();
			;
		}
		try {
			if (mediaPlayer == null) {
				return;
			}
			// mediaPlayer.setDataSource(file.getAbsolutePath());
			FileInputStream fis = new FileInputStream(file);
			mediaPlayer.setDataSource(fis.getFD());
//			mediaPlayer.setDataSource(fis.getFD(), 0, 4459811);//FIXME
			mediaPlayer.prepareAsync();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
			mediaPlayer.setOnCompletionListener(this);
			mediaPlayer.setOnErrorListener(this);
			mediaPlayer.setOnPreparedListener(this);
			// 设置是否循环播放
			mediaPlayer.setLooping(false);
		} catch (IllegalStateException e) {
			mediaPlayer.release();
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public AudioPlayer(Context context, InputStream is)
			throws IllegalArgumentException, IllegalStateException, IOException {
		if (mediaPlayer == null) {
			// 创建播放实例
			mediaPlayer
					.setDataSource("http://www.mobvcasting.com/android/audio/goodmorningandroid.mp3");

			// mediaPlayer.prepare();
			// mediaPlayer.start();
			mediaPlayer.prepareAsync();//
		}
		if (mediaPlayer == null) {
			return;
		}
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		// 设置是否循环播放
		mediaPlayer.setLooping(false);
		// 设置播放起始点
		mediaPlayer.seekTo(0);
		// 开始播放
		mediaPlayer.start();
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		mp.release();
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		mp.release();

	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// 设置播放起始点
		mediaPlayer.seekTo(0);
		// 开始播放
		mediaPlayer.start();
	}
}
